

package com.maoshi.shop.distribution.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.distribution.api.param.DistributionWithdrawCashSaceParam;
import com.maoshi.shop.distribution.comment.dto.DistributionWithdrawCashDto;
import com.maoshi.shop.distribution.comment.dto.DistributionWithdrawCashSetDto;
import com.maoshi.shop.distribution.comment.model.DistributionUser;
import com.maoshi.shop.distribution.comment.model.DistributionWithdrawCashSet;
import com.maoshi.shop.distribution.comment.param.RangeTimeParam;
import com.maoshi.shop.distribution.comment.service.DistributionUserService;
import com.maoshi.shop.distribution.comment.service.DistributionUserWalletService;
import com.maoshi.shop.distribution.comment.service.DistributionWithdrawCashService;
import com.maoshi.shop.distribution.comment.service.DistributionWithdrawCashSetService;
import com.maoshi.shop.security.api.util.SecurityUtils;
import com.maoshi.shop.security.comment.model.AppConnect;
import com.maoshi.shop.security.comment.service.AppConnectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;


/**
 * 分销提现
 */
@RestController
@RequestMapping("/p/distribution/withdrawCash")
@Api(tags = "分销员提现接口")
@AllArgsConstructor
public class DistributionWithdrawCashController {

    private DistributionWithdrawCashService distributionWithdrawCashService;

    private DistributionWithdrawCashSetService distributionWithdrawCashSetService;

    private DistributionUserService distributionUserService;

    private MapperFacade mapperFacade;

    private DistributionUserWalletService distributionUserWalletService;

    private final AppConnectService appConnectService;


    @GetMapping("/info")
    @ApiOperation(value = "获取提现设置信息")
    public ResponseEntity<DistributionWithdrawCashSetDto> setInfo() {
        DistributionWithdrawCashSet set = distributionWithdrawCashSetService.getByShopId();
        return ResponseEntity.ok(mapperFacade.map(set, DistributionWithdrawCashSetDto.class));
    }


    @GetMapping("/page")
    @ApiOperation(value = "分页查看提现记录")
    public ResponseEntity<IPage<DistributionWithdrawCashDto>> page(PageParam<DistributionWithdrawCashDto> page) {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            throw new MaoshiShopBindException("您还不是分销员");
        }
        return ResponseEntity.ok(distributionWithdrawCashService.distributionWithdrawCashDtoPageByUserId(page, distributionUser.getDistributionUserId()));
    }

    @PostMapping("/apply")
    @ApiOperation(value = "用户发起提现申请", notes = "填入提现参数")
    public ResponseEntity<Void> apply(@Valid @RequestBody DistributionWithdrawCashSaceParam distributionWithdrawCashSaceParam) {
        String userId = SecurityUtils.getUser().getUserId();
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, Constant.PLATFORM_SHOP_ID);
        if (distributionUser == null || distributionUser.getState() != 1) {
            throw new MaoshiShopBindException("未找到分销员信息或分销员不在正常状态，请稍后重试");
        }
        AppConnect appConnect = appConnectService.getOne(new LambdaQueryWrapper<AppConnect>()
                .eq(AppConnect::getUserId, distributionUser.getUserId())
                .eq(AppConnect::getAppId, 1));
        if (appConnect == null) {
          throw new MaoshiShopBindException("未找到此用户信息");
        }
        //发起提现
        distributionWithdrawCashService.apply(distributionWithdrawCashSaceParam.getAmount(), distributionUser, appConnect);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/isWithdrawCash")
    @ApiOperation(value = "当前是否可以提现")
    public ResponseEntity<Boolean> isWithdrawCash() {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        Long distributionUserId = distributionUser.getDistributionUserId();
        //获取店铺提现设置
        DistributionWithdrawCashSet distributionWithdrawCashSet = distributionWithdrawCashSetService.getByShopId();

        //获取店铺设置的提现频率算出时间区间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - distributionWithdrawCashSet.getFrequency());
        //获取玩家最近的提现次数
        //判断是否能够提现
        if (distributionWithdrawCashService.getCountByRangeTimeAndDistributionUserId(new RangeTimeParam(calendar.getTime(), new Date()), distributionUserId) >= distributionWithdrawCashSet.getNumber()) {
            throw new MaoshiShopBindException("提现次数为" + distributionWithdrawCashSet.getFrequency() + "天" + distributionWithdrawCashSet.getNumber() + "次");
        }
        return ResponseEntity.ok(true);
    }

    @GetMapping("/totalWithdrawCash")
    @ApiOperation(value = "查看用户总提现金额")
    public ResponseEntity<Double> getUserTotalWithdrawCash() {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            throw new MaoshiShopBindException("未找到分销员信息");
        }
        Long distributionUserId = distributionUser.getDistributionUserId();
        Long walletId = distributionUserWalletService.getWalletIdByDistributionUserId(distributionUserId);
        Double totalWithdrawCash = distributionWithdrawCashService.getUserTotalWithdrawCash(walletId);
        return ResponseEntity.ok(totalWithdrawCash);
    }

}
